<template>
  <div class="document-detail">
    <div v-if="!document" class="no-document">
      <div class="placeholder">
        <h3>选择一个文档</h3>
        <p>从左侧树中选择一个文档来查看详情</p>
      </div>
    </div>

    <div v-else class="document-view">
      <div class="detail-header">
        <!-- 标题行：左边展开图标 + 中间标题 + 右边展开图标 -->
        <div class="title-row">
          <img src="@/assets/icon/expand.svg" alt="expand"
               class="expand-icon left"
               @click="handleToggleSidebar"
               title="显示/隐藏侧边栏"/>
          <h2 class="document-title">{{ document.name }}</h2>
          <img src="@/assets/icon/expand.svg" alt="expand"
               class="expand-icon right"
               @click="handleToggleDocToc"
               title="显示/隐藏文档目录"/>
        </div>

        <!-- 信息和操作行：左边创建时间 + 右边操作按钮 -->
        <div class="info-actions-row">
          <div class="creation-time">
            <el-icon>
              <Calendar/>
            </el-icon>
            <span>{{ document.createdTime }}</span>
          </div>

          <div class="header-actions">
            <!-- 操作按钮 -->
            <el-button type="primary" :icon="Edit" circle @click="onEdit" title="编辑"/>

            <el-button v-if="document.id !== '-1'" type="primary" :icon="Plus" circle @click="showCreateItemDialog"
                       title="添加子项"/>

            <!-- 文档操作下拉菜单 -->
            <div v-if="document.id !== '-1'" class="document-actions-dropdown">
              <el-button type="info" :icon="More" circle @click="toggleDocumentActionsMenu" title="更多操作"/>
              <div v-if="showDocumentActionsMenu" class="dropdown-menu" @click.stop>
                <!-- 收藏操作 -->
                <div class="dropdown-section">
                  <button @click="toggleFavoriteFromDropdown" class="dropdown-item" :disabled="favoriteLoading">
                    {{ favoriteLoading ? '处理中...' : (isFavorited ? '取消收藏' : '收藏文档') }}
                  </button>
                </div>

                <!-- Markdown主题选择器 -->
                <div class="dropdown-section">
                  <div class="dropdown-label">Markdown样式</div>
                  <div class="dropdown-style-control">
                    <select v-model="markdownTheme" @change="saveMarkdownTheme" class="style-selector-dropdown">
                      <option v-for="option in themeOptions" :key="option.value" :value="option.value">
                        {{ option.label }}
                      </option>
                    </select>
                  </div>
                </div>
                <!-- 布局模式切换 -->
                <div v-if="documentItems.length > 0" class="dropdown-section">
                  <div class="dropdown-label">显示模式</div>
                  <button @click="switchDisplayModeFromDropdown('grid')"
                          class="dropdown-item"
                          :class="{ active: displayMode === 'grid' }">
                    网格显示
                  </button>
                  <button @click="switchDisplayModeFromDropdown('waterfall')"
                          class="dropdown-item"
                          :class="{ active: displayMode === 'waterfall' }">
                    瀑布流显示
                  </button>
                </div>

                <!-- 列数控制 -->
                <div v-if="documentItems.length > 0" class="dropdown-section">
                  <div class="dropdown-label">列数设置</div>
                  <div class="dropdown-grid-control">
                    <select
                        v-model="itemGridColumns"
                        @change="saveItemGridColumns"
                        class="columns-selector-dropdown"
                    >
                      <option value="1">1列</option>
                      <option value="2">2列</option>
                      <option value="3">3列</option>
                      <option value="4">4列</option>
                      <option value="5">5列</option>
                      <option value="6">6列</option>
                    </select>
                  </div>
                </div>

                <!-- 样式选择器 -->
                <div v-if="documentItems.length > 0" class="dropdown-section">
                  <div class="dropdown-label">卡片样式</div>
                  <div class="dropdown-style-control">
                    <select v-model="itemStyle" @change="saveItemStyle" class="style-selector-dropdown">
                      <option value="default">默认样式</option>
                      <option value="minimal">简洁样式</option>
                      <option value="card">卡片样式</option>
                    </select>
                  </div>
                </div>

                <!-- 已完成项显示控制 -->
                <div v-if="documentItems.length > 0 && completedCount > 0" class="dropdown-section">
                  <button @click="toggleCompletedItems" class="dropdown-item" :class="{ active: showCompletedItems }">
                    {{ showCompletedItems ? '隐藏已完成' : '显示已完成' }}
                    <span class="completed-count-inline" v-if="!showCompletedItems">
                      ({{ completedCount }})
                    </span>
                  </button>
                </div>

                <!-- 文档信息 -->
                <div v-if="documentItems.length === 0" class="dropdown-section">
                  <div class="dropdown-item-info">
                    暂无子项
                  </div>
                </div>

                <!-- 删除操作 -->
                <div class="dropdown-section">
                  <button @click="onDelete" class="dropdown-item danger">
                    删除文档
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 文档内容区域 -->
      <div class="document-content">
        <div v-if="document?.content && document.content.trim()" class="content-body">
          <MarkdownRenderer
              :content="document.content"
              :theme="markdownTheme"/>
        </div>
      </div>

      <!-- 文档子项列表 -->
      <div class="items-section">
        <!-- 网格布局 -->
        <div v-if="filteredDocumentItems.length > 0 && displayMode === 'grid'" class="items-list grid-layout"
             :style="itemGridStyle">
          <ItemCard
              v-for="item in filteredDocumentItems"
              :key="item.id"
              :item="item"
              :style="itemStyle"
              :markdown-theme="markdownTheme"
              @edit="editItem"
          >
            <template #actions="{ item }: { item: any }">
              <div class="action-dropdown" :class="{ 'active': activeDropdown === item.id }">
                <button
                    @click="toggleDropdown(item.id)"
                    class="dropdown-toggle"
                    title="操作"
                >
                  ⋯
                </button>
                <div class="dropdown-menu" v-if="activeDropdown === item.id">
                  <button @click="editItem(item)" class="dropdown-item">
                    编辑
                  </button>
                  <button
                      @click="toggleItemComplete(item)"
                      class="dropdown-item complete-item"
                      :class="{ 'completed': item.completed }"
                  >
                    {{ item.completed ? '取消完成' : '标记完成' }}
                  </button>
                  <button
                      @click="toggleItemTop(item)"
                      class="dropdown-item top-item"
                      :class="{ 'topped': item.isTop }"
                  >
                    {{ item.isTop ? '取消置顶' : '置顶' }}
                  </button>
                  <div class="dropdown-divider"></div>
                  <button @click="deleteItem(item)" class="dropdown-item delete-item">
                    删除
                  </button>
                </div>
              </div>
            </template>

          </ItemCard>
        </div>

        <!-- 瀑布流布局 -->
        <WaterfallLayout
            v-if="filteredDocumentItems.length > 0 && displayMode === 'waterfall'"
            :items="filteredDocumentItems"
            class="waterfall-layout"
            :min-column-width="280"
            :columns="responsiveColumns"
        >
          <template #default="{ item }">
            <ItemCard
                :item="item"
                :style="itemStyle"
                :markdown-theme="markdownTheme"
                class="waterfall-card"
                @edit="editItem"
            >
              <template #actions="{ item }: { item: any }">
                <el-dropdown trigger="click">
                  <el-icon style="font-size: 1.2rem;">
                    <More/>
                  </el-icon>

                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="editItem(item)" style="color: #00b894;">编辑</el-dropdown-item>

                      <el-dropdown-item @click="toggleItemComplete(item)">完成</el-dropdown-item>

                      <el-dropdown-item @click="toggleItemTop(item)">置顶</el-dropdown-item>

                      <el-dropdown-item @click="deleteItem(item)" divided style="color: #eb5757;">删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </ItemCard>
          </template>
        </WaterfallLayout>
      </div>
    </div>
  </div>

  <!-- 文档子项创建/编辑弹窗 -->
  <div v-if="showItemDialog" class="dialog-overlay" @click="closeItemDialog">
    <div class="dialog" @click.stop>
      <div class="dialog-header">
        <h3>{{ isEditingItem ? '编辑文档子项' : '添加文档子项' }}</h3>
        <button @click="closeItemDialog" class="close-btn">✕</button>
      </div>
      <form @submit.prevent="submitItemForm" class="dialog-form">
        <div class="form-group">
          <label for="itemName">子项名称：</label>
          <input
              id="itemName"
              v-model="itemFormData.name"
              type="text"
              placeholder="请输入子项名称（可选）"
              class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="itemSpace">所属空间：</label>
          <select
              id="itemSpace"
              v-model="selectedSpaceId"
              class="form-input"
              :disabled="loadingSpaces"
              @change="onSpaceChange(selectedSpaceId)"
          >
            <option value="">{{ loadingSpaces ? '加载中...' : '请选择空间' }}</option>
            <option
                v-for="space in availableSpaces"
                :key="space.id"
                :value="space.id"
            >
              {{ space.name }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label for="itemDocument">所属文档：</label>
          <select
              id="itemDocument"
              v-model="itemFormData.documentId"
              class="form-input"
              :disabled="loadingDocuments || !selectedSpaceId"
          >
            <option value="">
              {{
                !selectedSpaceId ? '请先选择空间' :
                    loadingDocuments ? '加载中...' :
                        '请选择文档'
              }}
            </option>
            <option
                v-for="doc in availableDocuments"
                :key="doc.id"
                :value="doc.id"
            >
              {{ doc.name }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label for="itemContent">子项内容：</label>
          <textarea
              id="itemContent"
              v-model="itemFormData.content"
              placeholder="请输入子项内容（支持Markdown）"
              class="form-input form-textarea"
              rows="8"
              @keydown="handleKeyDown"
          ></textarea>
        </div>
        <div class="form-group">
          <label for="itemSortNo">排序号：</label>
          <input
              id="itemSortNo"
              v-model.number="itemFormData.sortNo"
              type="number"
              placeholder="可选，用于排序（默认为0）"
              class="form-input"
          />
        </div>
        <div class="form-group">
          <label>星级评分：</label>
          <div class="star-rating">
              <span
                  v-for="star in 5"
                  :key="star"
                  class="star"
                  :class="{ 'star-filled': star <= (itemFormData.starRating || 0) }"
                  @click="setStarRating(star)"
                  @mouseover="hoverStarRating = star"
                  @mouseleave="hoverStarRating = 0"
                  :title="`${star}星`"
              >
                {{ star <= (hoverStarRating || itemFormData.starRating || 0) ? '★' : '☆' }}
              </span>
            <button
                type="button"
                v-if="itemFormData.starRating && itemFormData.starRating > 0"
                @click="clearStarRating"
                class="clear-rating-btn"
                title="清除评分"
            >
              ✕
            </button>
          </div>
        </div>
        <div class="dialog-actions">
          <button type="button" @click="closeItemDialog" class="cancel-btn">取消</button>
          <button type="submit" :disabled="submittingItem" class="submit-btn">
            {{ submittingItem ? '保存中...' : (isEditingItem ? '更新' : '创建') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, watch, computed, onMounted, onUnmounted, inject} from 'vue'
import {Edit, Plus, More, Calendar} from '@element-plus/icons-vue'
import type {Doc, DocumentItem, DocumentItemRequest, LayoutType} from '@/modules/doc/types/doc.ts'
import type {NameSpace} from '@/modules/doc/types/namespace.ts'
import MarkdownRenderer, {type MarkdownTheme} from '@/components/MarkdownRenderer.vue'
import WaterfallLayout from '@/components/WaterfallLayout.vue'
import {type ItemStyleType} from '@/components/ItemStyleSelector.vue'
import ItemCard from '@/modules/doc/components/item-card.vue'
import {useDoc, useDocDetail} from '@/modules/doc/composables'
import {documentItemApi, namespaceApi} from '@/modules/doc/api'
import {toast} from '@/utils/message.ts'

interface Props {
  document: Doc | null
  currentSpaceId?: string | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  edit: [document: Doc]
  create: [document: Omit<Doc, 'id' | 'createdTime' | 'updatedTime' | 'children'>]
  delete: [id: string]
  select: [document: Doc]
  refresh: []
  'toggle-left-drawer': []
  'toggle-right-drawer': []
}>()

// 使用 composables
const {fetchDocumentsByNamespace, updateDocument} = useDoc()
const {fetchDocumentDetail} = useDocDetail()

// 注入父组件的布局控制方法和状态
const toggleSidebar = inject<() => void>('toggleSidebar')
// const showSidebar = inject('showSidebar', ref(true))
const toggleToc = inject<() => void>('toggleToc')
const isTocVisible = inject('isTocVisible', ref(true))

// 检测是否为移动端
const isMobile = () => {
  return window.innerWidth <= 768
}

// 展开按钮点击处理
const handleToggleSidebar = () => {
  if (isMobile()) {
    // 移动端模式：触发左侧抽屉切换
    emit('toggle-left-drawer')
  } else {
    // PC端模式：切换PC端侧边栏
    if (toggleSidebar) {
      toggleSidebar()
    }
  }
}

const handleToggleDocToc = async () => {
  if (isMobile()) {
    // 移动端模式：触发右侧抽屉切换
    emit('toggle-right-drawer')
    return
  }

  // PC端模式：切换PC端目录显示和保存到数据库
  // 先计算新的状态值
  const newShowToc = !isTocVisible.value

  if (toggleToc) {
    toggleToc()
  }

  // 同时更新文档的isShowToc字段
  if (props.document && props.document.id !== '-1') {
    try {
      await updateDocument(props.document.id, {
        ...props.document,
        isShowToc: newShowToc
      })
    } catch (error: any) {
      console.error('保存目录显示设置失败:', error)
      // 静默失败，不显示错误提示，因为这是辅助功能
    }
  }
}

// Markdown样式相关状态
const markdownTheme = ref<MarkdownTheme>('classic')

// Markdown主题选项
const themeOptions = [
  {value: 'classic', label: '经典'},
  {value: 'minimal', label: '简约'}
] as const

// 文档子项样式相关状态
const itemStyle = ref<ItemStyleType>('default')

// 编辑功能已移至独立页面

// 文档子项相关状态
const documentItems = ref<DocumentItem[]>([])

// 子项弹窗相关状态
const showItemDialog = ref(false)
const isEditingItem = ref(false)
const editingItemId = ref<string | null>(null)
const submittingItem = ref(false)
const itemFormData = ref<DocumentItemRequest>({
  documentId: '',
  name: '',
  content: '',
  sortNo: 0,
  starRating: 0,
  completed: false
})

// 可选择的空间和文档列表
const availableSpaces = ref<NameSpace[]>([])
const availableDocuments = ref<Doc[]>([])
const selectedSpaceId = ref<string>('')
const loadingSpaces = ref(false)
const loadingDocuments = ref(false)

// 收藏相关状态
const isFavorited = ref(false)
const favoriteLoading = ref(false)

// 显示模式相关状态
const displayMode = ref<'grid' | 'waterfall' | 'markdown'>('grid')

// 文档子项网格列数控制
const itemGridColumns = ref(3)

// 星级评分相关状态
const hoverStarRating = ref(0)

// 显示已完成子项的控制
const showCompletedItems = ref(false)


// 控制当前激活的下拉菜单
const activeDropdown = ref<string | null>(null)

// 文档操作下拉菜单控制
const showDocumentActionsMenu = ref(false)

// 过滤后的文档子项（根据是否显示已完成项）
const filteredDocumentItems = computed(() => {
  if (showCompletedItems.value) {
    return documentItems.value
  }
  return documentItems.value.filter(item => !item.completed)
})

// 已完成子项数量
const completedCount = computed(() => {
  return documentItems.value.filter(item => item.completed).length
})

// 文档子项网格样式
const itemGridStyle = computed(() => ({
  'grid-template-columns': `repeat(${itemGridColumns.value}, 1fr)`
}))

// 响应式列数计算（用于瀑布流）
const responsiveColumns = computed(() => {
  // 在移动端或平板端需要限制列数
  if (typeof window !== 'undefined') {
    const width = window.innerWidth
    if (width <= 768) {
      return 1 // 移动端单列
    } else if (width <= 1024) {
      return Math.min(itemGridColumns.value, 2) // 平板端最多2列
    }
  }
  return itemGridColumns.value // 桌面端不限制
})

// 监听displayMode变化（用于调试，生产环境可移除）
// watch(() => displayMode.value, (newMode, oldMode) => {
//   console.log('displayMode从', oldMode, '变更为', newMode)
// }, { immediate: true })

// 布局类型映射
const layoutTypeMap = {
  grid: 'GRAD' as LayoutType,
  waterfall: 'WATERFALL' as LayoutType
}

const displayModeMap: Record<LayoutType, 'grid' | 'waterfall' | 'markdown'> = {
  GRAD: 'grid',
  WATERFALL: 'waterfall',
  markdown: 'grid', // markdown类型默认显示为网格
  list: 'grid',     // list类型默认显示为网格  
  grid: 'grid'      // grid类型显示为网格
}

// 编辑功能已移至独立页面

// 设置星级评分
const setStarRating = (rating: number) => {
  itemFormData.value.starRating = rating
}

// 清除星级评分
const clearStarRating = () => {
  itemFormData.value.starRating = 0
}

// 切换下拉菜单显示
const toggleDropdown = (itemId: string | undefined) => {
  if (!itemId) return
  activeDropdown.value = activeDropdown.value === itemId ? null : itemId
}

// 切换文档操作下拉菜单
const toggleDocumentActionsMenu = () => {
  showDocumentActionsMenu.value = !showDocumentActionsMenu.value
}

// 从下拉菜单切换显示模式
const switchDisplayModeFromDropdown = async (mode: 'grid' | 'waterfall') => {
  showDocumentActionsMenu.value = false
  await switchDisplayMode(mode)
}

// 从下拉菜单切换已完成项显示
const toggleCompletedItems = () => {
  showCompletedItems.value = !showCompletedItems.value
  showDocumentActionsMenu.value = false
}

// 从下拉菜单切换收藏状态
const toggleFavoriteFromDropdown = async () => {
  showDocumentActionsMenu.value = false
  await toggleFavorite()
}

// 切换子项完成状态
const toggleItemComplete = async (item: DocumentItem) => {
  if (!item.id) return

  try {
    await documentItemApi.toggleComplete(item.id)
    // 关闭下拉菜单
    activeDropdown.value = null
    // 触发刷新以重新加载文档数据（包含更新的子项列表）
    emit('refresh')
    toast.success(item.completed ? '已取消完成' : '已标记为完成')
  } catch (error: any) {
    console.error('切换完成状态失败:', error)
    toast.error('操作失败，请稍后重试')
  }
}

// 切换子项置顶状态
const toggleItemTop = async (item: DocumentItem) => {
  if (!item.id) return

  try {
    // 使用 update API 更新置顶状态
    const updatedItem: DocumentItemRequest = {
      documentId: item.documentId,
      name: item.name,
      content: item.content,
      sortNo: item.sortNo || 0,
      starRating: item.starRating || 0,
      completed: item.completed || false,
      isTop: !item.isTop // 切换置顶状态
    }

    await documentItemApi.update(item.id, updatedItem)
    // 关闭下拉菜单
    activeDropdown.value = null
    // 触发刷新以重新加载文档数据（包含更新的子项列表）
    emit('refresh')
    toast.success(item.isTop ? '已取消置顶' : '已置顶')
  } catch (error: any) {
    console.error('切换置顶状态失败:', error)
    toast.error('操作失败，请稍后重试')
  }
}

// 进入编辑模式
const onEdit = async () => {
  if (props.document) {
    // 发射编辑事件给父组件处理
    emit('edit', props.document)
  }
}


const onDelete = async () => {
  if (!props.document) return

  const confirmed = await toast.confirm(
      '确定要删除这个文档吗？此操作不可撤销。',
      {
        title: '删除文档',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }
  )

  if (confirmed) {
    emit('delete', props.document.id)
  }
}


// 从文档数据中加载子项
const loadDocumentItems = (document: Doc | null) => {
  if (!document || document.id === '-1') {
    documentItems.value = []
    return
  }

  // 直接从文档数据中获取子项列表
  documentItems.value = document.items || []
}

// 显示创建子项弹窗
// 加载所有可用空间列表
const loadAvailableSpaces = async () => {
  if (loadingSpaces.value) return

  try {
    loadingSpaces.value = true
    const namespaces = await namespaceApi.getAll()
    availableSpaces.value = namespaces
  } catch (error) {
    console.error('加载空间列表失败:', error)
    toast.error('加载空间列表失败')
  } finally {
    loadingSpaces.value = false
  }
}

// 根据选择的空间加载对应的文档列表
const loadDocumentsBySpace = async (spaceId: string) => {
  if (!spaceId || loadingDocuments.value) {
    availableDocuments.value = []
    return
  }

  try {
    loadingDocuments.value = true
    const documents = await fetchDocumentsByNamespace(spaceId, {
      flatten: true,
      sort: true,
      showLoading: false
    })
    availableDocuments.value = documents
  } catch (error) {
    console.error('加载文档列表失败:', error)
    toast.error('加载文档列表失败')
    availableDocuments.value = []
  } finally {
    loadingDocuments.value = false
  }
}

// 监听空间选择变化
const onSpaceChange = async (spaceId: string) => {
  selectedSpaceId.value = spaceId
  // 清空文档选择
  itemFormData.value.documentId = ''
  // 加载对应空间的文档
  await loadDocumentsBySpace(spaceId)
}

const showCreateItemDialog = async () => {
  if (!props.document) {
    toast.warning('请先选择一个文档')
    return
  }

  // 加载可用空间列表
  await loadAvailableSpaces()

  isEditingItem.value = false
  editingItemId.value = null

  // 预设当前文档所属的空间
  const currentSpaceId = props.currentSpaceId || props.document.namespaceId || ''
  selectedSpaceId.value = currentSpaceId

  // 如果有空间，加载对应的文档列表
  if (currentSpaceId) {
    await loadDocumentsBySpace(currentSpaceId)
  }

  itemFormData.value = {
    documentId: props.document.id,
    name: '',
    content: '',
    sortNo: documentItems.value.length + 1,
    starRating: 0,
    completed: false
  }
  showItemDialog.value = true
}

// 编辑子项
const editItem = async (item: DocumentItem) => {
  // 关闭下拉菜单
  activeDropdown.value = null

  // 加载可用空间列表
  await loadAvailableSpaces()

  // 找到子项所属的文档，获取其空间ID
  let targetSpaceId = ''
  try {
    const targetDocument = await fetchDocumentDetail(item.documentId, {
      showLoading: false,
      showError: false
    })
    targetSpaceId = targetDocument?.namespaceId || ''
  } catch (error) {
    console.warn('获取子项所属文档失败:', error)
    targetSpaceId = props.currentSpaceId || ''
  }

  selectedSpaceId.value = targetSpaceId

  // 加载对应空间的文档列表
  if (targetSpaceId) {
    await loadDocumentsBySpace(targetSpaceId)
  }

  isEditingItem.value = true
  editingItemId.value = item.id || null
  itemFormData.value = {
    documentId: item.documentId,
    name: item.name,
    content: item.content,
    sortNo: item.sortNo || 0,
    starRating: item.starRating || 0,
    completed: item.completed || false
  }
  showItemDialog.value = true
}

// 删除子项
const deleteItem = async (item: DocumentItem) => {
  if (!item.id) return

  // 关闭下拉菜单
  activeDropdown.value = null

  const confirmed = await toast.confirm(
      `确定要删除子项"${item.name}"吗？此操作不可撤销。`,
      {
        title: '删除子项',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }
  )

  if (!confirmed) return

  try {
    await documentItemApi.delete(item.id)
    toast.success('子项删除成功')
    // 触发刷新以重新加载文档数据（包含更新的子项列表）
    emit('refresh')
  } catch (error: any) {
    console.error('删除子项失败:', error)
    toast.error('删除子项失败')
  }
}

// 关闭子项弹窗
const closeItemDialog = () => {
  showItemDialog.value = false
  isEditingItem.value = false
  editingItemId.value = null
  itemFormData.value = {
    documentId: '',
    name: '',
    content: '',
    sortNo: 0,
    starRating: 0,
    completed: false
  }
  submittingItem.value = false
}

// 提交子项表单
const submitItemForm = async () => {
  if (!props.document) return

  // 验证名称和内容不能都为空
  const hasName = itemFormData.value.name?.trim()
  const hasContent = itemFormData.value.content?.trim()

  if (!hasName && !hasContent) {
    toast.warning('子项名称和内容不能都为空，请至少填写一项')
    return
  }

  submittingItem.value = true

  try {
    if (isEditingItem.value && editingItemId.value) {
      // 更新子项
      await documentItemApi.update(editingItemId.value, itemFormData.value)
      toast.success('子项更新成功')
    } else {
      // 创建新子项
      await documentItemApi.create(itemFormData.value)
      toast.success('子项创建成功')
    }
    closeItemDialog()
    // 触发刷新以重新加载文档数据（包含更新的子项列表）
    emit('refresh')
  } catch (error: any) {
    console.error('保存子项失败:', error)
    toast.error('保存子项失败')
  } finally {
    submittingItem.value = false
  }
}

// 检查文档是否已收藏
const checkFavoriteStatus = (document: Doc) => {
  // 从文档数据中获取收藏状态
  isFavorited.value = document.isFavorite || false
}

// 切换收藏状态
const toggleFavorite = async () => {
  if (!props.document) return

  favoriteLoading.value = true
  try {
    const newFavoriteStatus = !isFavorited.value

    // 调用文档更新接口，传递isFavorite字段
    await updateDocument(props.document.id, {
      ...props.document,
      isFavorite: newFavoriteStatus
    })

    isFavorited.value = newFavoriteStatus
    toast.success(newFavoriteStatus ? '收藏成功' : '取消收藏成功')

    // 触发刷新以重新加载文档数据
    emit('refresh')
  } catch (error: any) {
    console.error('切换收藏状态失败:', error)
    toast.error('操作失败，请稍后重试')
  } finally {
    favoriteLoading.value = false
  }
}

// 监听文档变化，加载对应的子项
watch(() => props.document, (newDocument) => {

  if (newDocument && newDocument.id !== '-1') {
    loadDocumentItems(newDocument)
    checkFavoriteStatus(newDocument) // 检查收藏状态

    // 回显布局类型
    if (newDocument.layoutType && displayModeMap[newDocument.layoutType as LayoutType]) {
      displayMode.value = displayModeMap[newDocument.layoutType as LayoutType]
    } else {
      displayMode.value = 'grid' // 默认网格布局
    }
  } else if (newDocument && newDocument.id === '-1') {
    // 新文档逻辑
    documentItems.value = []
    isFavorited.value = false
    displayMode.value = 'grid'

    // 检查是否需要自动进入编辑模式
    if ((newDocument as any).isEditing) {
      onEdit()
    }
  } else {
    documentItems.value = []
    isFavorited.value = false
    displayMode.value = 'grid' // 重置为默认布局
  }
}, {immediate: true})

// 从localStorage读取markdown主题偏好
const savedMarkdownTheme = localStorage.getItem('markdownTheme') as MarkdownTheme
if (savedMarkdownTheme && themeOptions.some(option => option.value === savedMarkdownTheme)) {
  markdownTheme.value = savedMarkdownTheme
}

// 从localStorage读取子项样式偏好
const savedItemStyle = localStorage.getItem('itemStyle') as ItemStyleType
if (savedItemStyle && ['default', 'poster', 'card', 'minimal', 'timeline'].includes(savedItemStyle)) {
  itemStyle.value = savedItemStyle
}

// 保存Markdown主题到localStorage
const saveMarkdownTheme = () => {
  localStorage.setItem('markdownTheme', markdownTheme.value)
}

// 保存子项样式到localStorage
const saveItemStyle = () => {
  localStorage.setItem('itemStyle', itemStyle.value)
}

// 保存文档子项网格列数到localStorage
const saveItemGridColumns = () => {
  localStorage.setItem('itemGridColumns', itemGridColumns.value.toString())
}

// 从localStorage加载文档子项网格列数设置
const loadItemGridColumns = () => {
  const saved = localStorage.getItem('itemGridColumns')
  if (saved) {
    const columns = parseInt(saved)
    if (columns >= 1 && columns <= 6) {
      itemGridColumns.value = columns
    }
  }
}

// 切换布局模式并保存到后端
const switchDisplayMode = async (mode: 'grid' | 'waterfall') => {
  if (!props.document || props.document.id === '-1') {
    displayMode.value = mode
    return
  }

  try {
    const layoutType = layoutTypeMap[mode]
    await updateDocument(props.document.id, {
      ...props.document,
      layoutType
    })
    displayMode.value = mode
    toast.success(`已切换到${mode === 'grid' ? '网格' : '瀑布流'}布局`)
  } catch (error: any) {
    console.error('保存布局类型失败:', error)
    toast.error('保存布局设置失败')
  }
}

// 处理全局点击事件，关闭下拉菜单
const handleGlobalClick = (event: Event) => {
  const target = event.target as HTMLElement
  if (!target.closest('.action-dropdown')) {
    activeDropdown.value = null
  }
  if (!target.closest('.document-actions-dropdown')) {
    showDocumentActionsMenu.value = false
  }
}


// 生命周期钩子
onMounted(() => {
  document.addEventListener('click', handleGlobalClick)
  // 加载文档子项网格列数设置
  loadItemGridColumns()
})

onUnmounted(() => {
  document.removeEventListener('click', handleGlobalClick)
})

// 处理键盘按键事件（无序列表自动补全）
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    const textarea = event.target as HTMLTextAreaElement
    const {value, selectionStart} = textarea

    // 找到当前行的开始位置
    const beforeCursor = value.substring(0, selectionStart)
    const currentLineStart = beforeCursor.lastIndexOf('\n') + 1
    const currentLine = value.substring(currentLineStart, selectionStart)

    // 检查当前行是否以 "* " 开头（无序列表）
    const unorderedListMatch = currentLine.match(/^(\s*)\* (.*)$/)

    if (unorderedListMatch) {
      event.preventDefault()

      const [, indent, content] = unorderedListMatch

      // 如果当前行只有 "* " 且没有其他内容，则移除当前行的 "* "
      if (content.trim() === '') {
        // 删除当前行的 "* " 并保持在同一行
        const newValue = value.substring(0, currentLineStart) + indent + value.substring(selectionStart)
        textarea.value = newValue

        // 更新Vue的响应式数据
        if (textarea.id === 'itemContent') {
          itemFormData.value.content = newValue
        }

        // 设置光标位置
        const newCursorPosition = currentLineStart + indent.length
        textarea.setSelectionRange(newCursorPosition, newCursorPosition)
      } else {
        // 在下一行添加新的无序列表项
        const newListItem = `\n${indent}* `
        const newValue = value.substring(0, selectionStart) + newListItem + value.substring(selectionStart)
        textarea.value = newValue

        // 更新Vue的响应式数据
        if (textarea.id === 'itemContent') {
          itemFormData.value.content = newValue
        }

        // 设置光标位置到新列表项的末尾
        const newCursorPosition = selectionStart + newListItem.length
        textarea.setSelectionRange(newCursorPosition, newCursorPosition)
      }
    }
  }
}

// 暴露方法给父组件调用
defineExpose({
  onEdit
})
</script>

<style scoped>
.document-detail {
  display: flex;
  flex-direction: column;
  padding: 0.5rem;
  gap: 0.5rem;
  margin: 0;
  background: #FFFFFF;
}

.no-document {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder {
  text-align: center;
  color: #999;
}

.placeholder h3 {
  margin: 0 0 1rem 0;
  font-size: 1.5rem;
}

.placeholder p {
  margin: 0;
  font-size: 1rem;
}

.document-view {
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  flex-shrink: 0;
  position: relative;
}

.header-actions .el-button {
  margin: 0;
}

.title-row {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}

.expand-icon {
  width: 24px;
  height: 24px;
  opacity: 0.6;
  transition: opacity 0.2s ease;
  cursor: pointer;
}

.expand-icon:hover {
  opacity: 1;
}

.expand-icon.left {
  transform: rotate(180deg);
}

.expand-icon.right {
  /* 保持原方向 */
}

.document-title {
  margin: 0;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 600;
  text-align: center;
  flex: 1;
}

.info-actions-row {
  display: flex;
  justify-content: space-between;
  padding: 0 0.5rem;
}

.creation-time {
  font-size: 0.7rem;
  color: #666;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.creation-time span {
  color: #666;
}

.document-title-input {
  margin: 0;
  padding: 0.5rem;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 600;
  text-align: center;
  border: 2px solid #42b883;
  border-radius: 6px;
  background: white;
  min-width: 300px;
}

.document-title-input:focus {
  outline: none;
  border-color: #369870;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

/* 字数统计样式 */
.word-count-display {
  position: absolute;
  right: 2rem;
  top: 1rem;
}

.word-count-text {
  font-size: 0.85rem;
  color: #666;
  background: #e9ecef;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-weight: 500;
}

/* 头部主题选择器样式 */
.theme-selector-wrapper {
  margin-right: 0.5rem;
}

.theme-selector-header {
  padding: 0.4rem 0.8rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  color: #2c3e50;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 70px;
}

.theme-selector-header:hover {
  border-color: #42b883;
  background: #f9f9f9;
}

.theme-selector-header:focus {
  outline: none;
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.2);
}

.action-btn {
  padding: 0.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1.1rem;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.2rem;
  height: 2.2rem;
}

.edit-btn {
  background: #74b9ff;
  color: white;
}

.edit-btn:hover {
  background: #0984e3;
}

.delete-btn {
  background: #fd79a8;
  color: white;
}

.delete-btn:hover {
  background: #e84393;
}

.add-item-btn {
  background: #00b894;
  color: white;
}

.add-item-btn:hover {
  background: #00a085;
}


.save-btn {
  background: #00b894;
  color: white;
}

.save-btn:hover:not(:disabled) {
  background: #00a085;
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.cancel-btn {
  background: #fd79a8;
  color: white;
}

.cancel-btn:hover {
  background: #e84393;
}

.favorite-btn {
  background: #ffeaa7;
  color: #2d3436;
}

.favorite-btn:hover {
  background: #fdcb6e;
}

.favorite-btn.favorited {
  background: #e17055;
  color: white;
}

.favorite-btn.favorited:hover {
  background: #d63031;
}

.favorite-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 文档操作下拉菜单样式 */
.document-actions-dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-btn {
  background: #6c757d;
  color: white;
}

.dropdown-btn:hover {
  background: #5a6268;
}

.document-actions-dropdown .dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  min-width: 180px;
  min-height: auto;
  background: white;
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  z-index: 9999;
  padding: 0.5rem 0;
  margin-top: 0.25rem;
  overflow: visible;
  display: block;
}

.document-actions-dropdown .dropdown-section {
  padding: 0.5rem 0;
}

.document-actions-dropdown .dropdown-section:not(:last-child) {
  border-bottom: 1px solid #f0f0f0;
}

.document-actions-dropdown .dropdown-label {
  padding: 0.25rem 1rem;
  font-size: 0.8rem;
  color: #666;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.document-actions-dropdown .dropdown-item {
  width: 100%;
  padding: 0.5rem 1rem;
  border: none;
  background: transparent;
  cursor: pointer;
  text-align: left;
  font-size: 0.9rem;
  color: #2c3e50;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.document-actions-dropdown .dropdown-item:hover {
  background: #f8f9fa;
}

.document-actions-dropdown .dropdown-item.active {
  background: #42b883;
  color: white;
}

.document-actions-dropdown .dropdown-item.danger {
  color: #dc3545;
}

.document-actions-dropdown .dropdown-item.danger:hover {
  background: #fee;
  color: #dc3545;
}

.document-actions-dropdown .dropdown-grid-control,
.document-actions-dropdown .dropdown-style-control {
  padding: 0 1rem;
}

.document-actions-dropdown .columns-selector-dropdown,
.document-actions-dropdown .style-selector-dropdown {
  width: 100%;
  padding: 0.4rem 0.6rem;
  border: 1px solid #e1e1e1;
  border-radius: 4px;
  background: white;
  font-size: 0.85rem;
  color: #2c3e50;
  cursor: pointer;
  transition: all 0.2s ease;
}

.document-actions-dropdown .columns-selector-dropdown:hover,
.document-actions-dropdown .style-selector-dropdown:hover {
  background: #f8f9fa;
  border-color: #42b883;
}

.document-actions-dropdown .columns-selector-dropdown:focus,
.document-actions-dropdown .style-selector-dropdown:focus {
  outline: none;
  border-color: #42b883;
  background: #f8f9fa;
}

.document-actions-dropdown .completed-count-inline {
  font-size: 0.8rem;
  opacity: 0.8;
  margin-left: 0.25rem;
}

.document-actions-dropdown .dropdown-item-info {
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
  color: #666;
  font-style: italic;
  text-align: center;
}

.document-meta {
  padding: 1rem 2rem;
  background: #f8f9fa;
  border-bottom: 1px solid #e1e1e1;
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  flex-shrink: 0;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.meta-label {
  color: #666;
  font-size: 0.9rem;
  font-weight: 500;
}

.meta-value {
  color: #2c3e50;
  font-size: 0.9rem;
}

.document-content {
  flex: none;
  overflow-y: visible;
  padding: 0 0.5rem;
}

.edit-form .form-group {
  margin-bottom: 1.5rem;
}

.edit-form label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 600;
  font-size: 0.95rem;
}

.edit-form .form-select {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #42b883;
  border-radius: 6px;
  font-size: 1rem;
  background: white;
}

.edit-form .form-select:focus {
  outline: none;
  border-color: #369870;
}

.edit-form .form-select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 空间选项样式 */
.space-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0.25rem 0;
}

.space-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.space-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 0.9rem;
}

.space-desc {
  font-size: 0.75rem;
  color: #666;
  margin-top: 0.125rem;
}

.space-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.space-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.space-count {
  font-size: 0.75rem;
  color: #999;
  background: #f0f0f0;
  padding: 0.125rem 0.375rem;
  border-radius: 8px;
  font-weight: 500;
}

.content-editor {
  width: 100%;
  border: 2px solid #42b883;
  border-radius: 6px;
  padding: 1.5rem;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 1rem;
  line-height: 1.6;
  resize: none;
  overflow-y: auto;
  box-sizing: border-box;
}

.content-editor:focus {
  outline: none;
  border-color: #369870;
}

.content-editor.drag-over {
  border-color: #42b883;
  background-color: rgba(66, 184, 131, 0.05);
}

/* 编辑器工具栏样式 */
.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  padding: 0.5rem 0;
}

.toolbar-tip {
  font-size: 0.8rem;
  color: #666;
  font-style: italic;
}


.content-body {
  /* padding: 0 1.5rem 1.5rem 1.5rem; */
  min-height: 200px;
}

/* Markdown内容容器 */
.markdown-content {
  width: 100%;
}

/* 样式控件样式 */
.markdown-controls {
  padding: 0 0 1rem 0;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 1rem;
  display: flex;
  justify-content: flex-end;
}

.view-mode-controls {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.control-label {
  font-size: 0.9rem;
  color: #666;
  font-weight: 500;
}

.theme-selector {
  padding: 0.4rem 0.8rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  color: #2c3e50;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 80px;
}

.theme-selector:hover {
  border-color: #42b883;
  background: #f9f9f9;
}

.theme-selector:focus {
  outline: none;
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.2);
}

.raw-content {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 1rem;
  line-height: 1.6;
  color: #2c3e50;
}


.document-actions {
  padding: 1rem 2rem 2rem 2rem;
  border-top: 1px solid #e1e1e1;
  background: #f9f9f9;
  display: flex;
  gap: 1rem;
  flex-shrink: 0;
}

.primary-btn, .secondary-btn {
  padding: 0.7rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.primary-btn {
  background: #42b883;
  color: white;
}

.primary-btn:hover {
  background: #369870;
}

.secondary-btn {
  background: white;
  color: #666;
  border: 1px solid #e1e1e1;
}

.secondary-btn:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #42b883;
  color: #42b883;
}

.secondary-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  /* 移动端优化信息和操作行布局 */
  .info-actions-row {
    gap: 0.5rem;
  }

  .creation-time {
    font-size: 0.6rem;
  }

  .header-actions {
    gap: 0.4rem;
  }

  .title-row {
    gap: 0.5rem;
  }

  .expand-icon {
    width: 20px;
    height: 20px;
  }

  .document-title {
    font-size: 1.2rem;
  }

  .document-title-input {
    font-size: 1.2rem;
    min-width: 250px;
  }


  .word-count-display {
    position: static;
    order: -1;
  }

  .word-count-text {
    font-size: 0.8rem;
  }

  .content-editor {
    font-size: 0.9rem;
  }

  .theme-selector-wrapper {
    margin-right: 0;
    margin-bottom: 0.5rem;
  }

  .theme-selector-header {
    font-size: 0.8rem;
    padding: 0.3rem 0.6rem;
    min-width: 60px;
  }

  .document-meta {
    padding: 1rem;
    flex-direction: column;
    gap: 0.5rem;
  }


  .document-actions {
    padding: 1rem;
    flex-direction: column;
  }
}

/* 文档子项样式 */
.items-section {
  flex-shrink: 0;
  margin: 0.5rem 0.5rem;
}

.items-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding: 0 0.5rem;
}

.items-header h3 {
  margin: 0;
  color: #42b883;
  font-size: 1.2rem;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.show-completed-btn {
  padding: 0.5rem 0.75rem;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  color: #666;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.show-completed-btn:hover {
  background: #e8e8e8;
  border-color: #42b883;
  color: #42b883;
}

.show-completed-btn.active {
  background: #42b883;
  color: white;
  border-color: #42b883;
}

.completed-count {
  font-size: 0.8rem;
  opacity: 0.8;
}

/* 列数控制样式 */
.grid-control {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.control-label {
  font-size: 0.85rem;
  color: #666;
  font-weight: 400;
  white-space: nowrap;
}

.columns-selector {
  padding: 0.375rem 0.5rem;
  border: 1px solid #e1e1e1;
  border-radius: 4px;
  background: white;
  font-size: 0.85rem;
  color: #2c3e50;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 60px;
  height: 32px;
  box-sizing: border-box;
}

.columns-selector:hover {
  background: #f8f9fa;
  border-color: #42b883;
}

.columns-selector:focus {
  outline: none;
  border-color: #42b883;
  background: #f8f9fa;
}

.columns-selector option {
  background: white;
  color: #2c3e50;
}

/* 显示模式切换按钮样式 */
.display-mode-toggle {
  display: flex;
  background: #f5f5f5;
  border-radius: 6px;
  padding: 0.25rem;
  gap: 0.25rem;
}

.mode-btn {
  padding: 0.5rem 0.75rem;
  border: none;
  border-radius: 4px;
  background: transparent;
  color: #666;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 2.5rem;
  height: 2rem;
}

.mode-btn:hover {
  background: rgba(66, 184, 131, 0.1);
  color: #42b883;
}

.mode-btn.active {
  background: #42b883;
  color: white;
  font-weight: 600;
}


.no-items {
  text-align: center;
  padding: 3rem 0;
  color: #999;
}

.no-items p {
  margin: 0 0 1rem 0;
  font-size: 1rem;
}

/* 网格布局样式 */
.items-list.grid-layout {
  display: grid;
  gap: 0.5rem;
  align-items: stretch;
}

.item-card {
  background: white;
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  padding: 1rem;
  transition: all 0.2s;
  height: 100%;
  min-width: 250px;
  display: flex;
  flex-direction: column;
}

.item-card:hover {
  border-color: #42b883;
  box-shadow: 0 2px 8px rgba(66, 184, 131, 0.1);
}

.item-card.completed {
  opacity: 0.7;
  background: #f9f9f9;
  border-color: #ddd;
}

.item-card.completed .item-title {
  text-decoration: line-through;
  color: #999;
}

.item-card.completed .item-content {
  opacity: 0.6;
}

.item-card.completed:hover {
  opacity: 0.8;
  border-color: #00b894;
  box-shadow: 0 2px 8px rgba(0, 184, 148, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;
}

.item-title {
  margin: 0;
  color: #2c3e50;
  font-size: 1.1rem;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.item-header-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.item-rating-inline {
  display: flex;
  align-items: center;
}

.item-rating-inline .rating-star {
  font-size: 0.9rem;
  color: #ffd700;
}

.item-actions {
  display: flex;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.2s;
  position: relative;
}

.item-card:hover .item-actions {
  opacity: 1;
}

/* 下拉菜单样式 */
.action-dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-toggle {
  padding: 0.375rem;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 1rem;
  background: rgba(255, 255, 255, 0.9);
  color: #666;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(4px);
}

.dropdown-toggle:hover {
  background: rgba(255, 255, 255, 1);
  color: #333;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-dropdown.active .dropdown-toggle {
  background: #42b883;
  color: white;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(66, 184, 131, 0.3);
}

.action-dropdown.active {
  z-index: 999999;
}

.dropdown-menu {
  position: absolute;
  bottom: 100%;
  right: 0;
  min-width: 120px;
  background: white;
  border: 1px solid #e1e1e1;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 999999;
  overflow: hidden;
  margin-bottom: 0.25rem;
}

.dropdown-item {
  width: 100%;
  padding: 0.75rem 1rem;
  border: none;
  background: transparent;
  cursor: pointer;
  text-align: left;
  font-size: 0.9rem;
  color: #2c3e50;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.dropdown-item:hover {
  background: #f8f9fa;
}

.dropdown-item.complete-item.completed {
  color: #00b894;
}

.dropdown-item.top-item.topped {
  color: #e67e22;
}

.dropdown-divider {
  height: 1px;
  background: #e1e1e1;
  margin: 0.25rem 0;
}

.dropdown-item.delete-item {
  color: #dc3545;
}

.dropdown-item.delete-item:hover {
  background: #fee;
  color: #dc3545;
}

.item-content {
  margin-top: 0.5rem;
  padding: 0;
  background: transparent;
  border: none;
  flex: 1;
}

.item-meta {
  display: flex;
  gap: 1rem;
  font-size: 0.8rem;
  color: #666;
  border-top: 1px solid #f0f0f0;
  padding-top: 1rem;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

/* 瀑布流卡片样式 */
.waterfall-card {
  width: 100%;
  margin-bottom: 0.5rem;
}

/* 深色主题适配 */
.dark .document-detail {
  color: #e6e6e6;
}

.dark .document-title {
  color: #e6e6e6;
}

.dark .expand-icon {
  filter: invert(1);
}

.dark .creation-time {
  color: #b3b3b3;
}

.dark .creation-time span {
  color: #b3b3b3;
}

.dark .word-count-text {
  background: #3d3d3d;
  color: #b3b3b3;
}

.dark .document-title-input {
  background: #2d2d2d;
  color: #e6e6e6;
  border-color: #42b883;
}

.dark .content-body {
  color: #e6e6e6;
}

/* 深色模式下的Markdown控件样式 */
.dark .markdown-controls {
  border-bottom-color: #3d3d3d;
}

.dark .control-label {
  color: #b3b3b3;
}

.dark .theme-selector {
  background: #2d2d2d;
  border-color: #4a4a4a;
  color: #e6e6e6;
}

.dark .theme-selector:hover {
  background: #3d3d3d;
  border-color: #42b883;
}

.dark .theme-selector:focus {
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.3);
}

/* 深色模式下的头部主题选择器样式 */
.dark .theme-selector-header {
  background: #2d2d2d;
  border-color: #4a4a4a;
  color: #e6e6e6;
}

.dark .theme-selector-header:hover {
  background: #3d3d3d;
  border-color: #42b883;
}

.dark .theme-selector-header:focus {
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.3);
}

.dark .raw-content {
  color: #e6e6e6;
}

.dark .content-editor {
  background: #2d2d2d;
  color: #e6e6e6;
  border-color: #3d3d3d;
}

.dark .content-editor:focus {
  border-color: #42b883;
}

.dark .form-group label {
  color: #e6e6e6;
}

.dark .toolbar-tip {
  color: #b3b3b3;
}

.dark .no-document .placeholder {
  color: #e6e6e6;
}

.dark .no-document .placeholder h3 {
  color: #e6e6e6;
}

.dark .no-document .placeholder p {
  color: #b3b3b3;
}

.dark .action-btn {
  background: #2d2d2d;
  color: #e6e6e6;
  border: 1px solid #3d3d3d;
}

.dark .action-btn:hover {
  background: #3d3d3d;
}

.dark .save-btn {
  background: #42b883;
  color: white;
  border-color: #42b883;
}

.dark .save-btn:hover {
  background: #369870;
}

.dark .cancel-btn {
  background: #dc3545;
  color: white;
  border-color: #dc3545;
}

.dark .cancel-btn:hover {
  background: #c82333;
}

/* 深色主题下的文档操作下拉菜单样式 */
.dark .dropdown-btn {
  background: #495057;
  color: #e6e6e6;
}

.dark .dropdown-btn:hover {
  background: #3d4246;
}

.dark .document-actions-dropdown .dropdown-menu {
  background: #2d2d2d;
  border-color: #4a4a4a;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

.dark .document-actions-dropdown .dropdown-section:not(:last-child) {
  border-bottom-color: #4a4a4a;
}

.dark .document-actions-dropdown .dropdown-label {
  color: #b3b3b3;
}

.dark .document-actions-dropdown .dropdown-item {
  color: #e6e6e6;
}

.dark .document-actions-dropdown .dropdown-item:hover {
  background: #3d3d3d;
}

.dark .document-actions-dropdown .dropdown-item.active {
  background: #42b883;
  color: white;
}

.dark .document-actions-dropdown .dropdown-item.danger {
  color: #ff6b6b;
}

.dark .document-actions-dropdown .dropdown-item.danger:hover {
  background: #4a2a2a;
  color: #ff6b6b;
}

.dark .document-actions-dropdown .columns-selector-dropdown,
.dark .document-actions-dropdown .style-selector-dropdown {
  background: #2d2d2d;
  border-color: #4a4a4a;
  color: #e6e6e6;
}

.dark .document-actions-dropdown .columns-selector-dropdown:hover,
.dark .document-actions-dropdown .style-selector-dropdown:hover {
  background: #3d3d3d;
  border-color: #42b883;
}

.dark .document-actions-dropdown .columns-selector-dropdown:focus,
.dark .document-actions-dropdown .style-selector-dropdown:focus {
  background: #3d3d3d;
  border-color: #42b883;
}

.dark .document-actions-dropdown .completed-count-inline {
  color: #b3b3b3;
}

.dark .document-actions-dropdown .dropdown-item-info {
  color: #b3b3b3;
}

/* 深色主题下的子项样式 */
.dark .item-card {
  background: #2d2d2d;
  border-color: #3d3d3d;
}

.dark .item-card:hover {
  border-color: #42b883;
  box-shadow: 0 2px 8px rgba(66, 184, 131, 0.2);
}

.dark .item-title {
  color: #e6e6e6;
}


.dark .item-card.completed {
  background: #2a2a2a;
  border-color: #3d3d3d;
}

.dark .item-card.completed .item-title {
  color: #666;
}

/* 深色主题下的下拉菜单样式 */
.dark .dropdown-toggle {
  background: rgba(45, 45, 45, 0.9);
  color: #b3b3b3;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.dark .dropdown-toggle:hover {
  background: rgba(45, 45, 45, 1);
  color: #e6e6e6;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}

.dark .action-dropdown.active .dropdown-toggle {
  background: #42b883;
  color: white;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(66, 184, 131, 0.4);
}

.dark .dropdown-menu {
  background: #2d2d2d;
  border-color: #4a4a4a;
}

.dark .dropdown-item {
  color: #e6e6e6;
}

.dark .dropdown-item:hover {
  background: #3d3d3d;
}

.dark .dropdown-divider {
  background: #4a4a4a;
}

.dark .dropdown-item.delete-item {
  color: #ff6b6b;
}

.dark .dropdown-item.delete-item:hover {
  background: #4a2a2a;
  color: #ff6b6b;
}

.dark .item-content {
  background: transparent;
  border: none;
}

.dark .item-meta {
  color: #b3b3b3;
  border-top-color: #3d3d3d;
}

.dark .no-items {
  color: #b3b3b3;
}

/* 深色主题下的显示模式切换按钮 */
.dark .display-mode-toggle {
  background: #3d3d3d;
}

.dark .mode-btn {
  color: #b3b3b3;
}

.dark .mode-btn:hover {
  background: rgba(66, 184, 131, 0.2);
  color: #42b883;
}

.dark .mode-btn.active {
  background: #42b883;
  color: white;
}

/* 深色主题下的items-header */
.dark .items-header h3 {
  color: #42b883;
}

.dark .show-completed-btn {
  background: #3d3d3d;
  border-color: #4a4a4a;
  color: #b3b3b3;
}

.dark .show-completed-btn:hover {
  background: #4a4a4a;
  border-color: #42b883;
  color: #42b883;
}

.dark .show-completed-btn.active {
  background: #42b883;
  color: white;
  border-color: #42b883;
}

/* 深色模式下的列数控制样式 */
.dark .control-label {
  color: #b3b3b3;
}

.dark .columns-selector {
  background: #2d2d2d;
  border-color: #3d3d3d;
  color: #e6e6e6;
}

.dark .columns-selector:hover {
  background: #3d3d3d;
  border-color: #42b883;
}

.dark .columns-selector:focus {
  border-color: #42b883;
  background: #3d3d3d;
}

.dark .columns-selector option {
  background: #2d2d2d;
  color: #e6e6e6;
}


/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #999;
  padding: 0.25rem;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  color: #666;
  background: #f5f5f5;
}

.dialog-form {
  padding: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 500;
  font-size: 0.9rem;
}

.form-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #e1e1e1;
  border-radius: 4px;
  font-size: 0.9rem;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #42b883;
}

.form-textarea {
  min-height: 120px;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

.cancel-btn, .submit-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f8f8f8;
  color: #666;
}

.cancel-btn:hover {
  background: #e8e8e8;
}

.submit-btn {
  background: #42b883;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: #369870;
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 深色主题下的弹窗样式 */
.dark .dialog {
  background: #2d2d2d;
  color: #e6e6e6;
}

.dark .dialog-header {
  border-bottom-color: #3d3d3d;
}

.dark .dialog-header h3 {
  color: #e6e6e6;
}

.dark .close-btn {
  color: #b3b3b3;
}

.dark .close-btn:hover {
  color: #e6e6e6;
  background: #3d3d3d;
}

.dark .form-group label {
  color: #e6e6e6;
}

.dark .form-input {
  color: #e6e6e6;
}

.dark .form-input:focus {
  border-color: #42b883;
}

.dark .form-input::placeholder {
  color: #808080;
}

.dark .cancel-btn {
  background: #3d3d3d;
  color: #b3b3b3;
}

.dark .cancel-btn:hover {
  background: #4a4a4a;
}

/* 响应式网格适配 */
@media (max-width: 768px) {
  .items-list.grid-layout {
    grid-template-columns: 1fr !important; /* 移动端强制单列 */
  }

  .grid-control {
    display: none; /* 移动端隐藏列数控制 */
  }

  /* 瀑布流在移动端也限制为单列 */
  .waterfall-layout {
    --waterfall-columns: 1;
  }
}

@media (max-width: 1024px) and (min-width: 769px) {
  .items-list.grid-layout {
    grid-template-columns: repeat(2, 1fr) !important; /* 平板端最多2列 */
  }

  .columns-selector option[value="4"],
  .columns-selector option[value="5"],
  .columns-selector option[value="6"] {
    display: none; /* 平板端隐藏4-6列选项 */
  }

  /* 瀑布流在平板端最多2列 */
  .waterfall-layout {
    --waterfall-columns: 2;
  }
}

/* 星级评分样式 */
.star-rating {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.star {
  font-size: 1.2rem;
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
}

.star:hover {
  transform: scale(1.1);
}

.star-filled {
  color: #ffd700;
}

.clear-rating-btn {
  margin-left: 0.5rem;
  padding: 0.2rem 0.4rem;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  color: #666;
  transition: all 0.2s;
}

.clear-rating-btn:hover {
  background: #e8e8e8;
  color: #333;
}

/* 通用星级样式 */
.rating-star {
  font-size: 1rem;
  color: #ffd700;
}

/* 深色主题下的星级样式 */
.dark .star-rating {
  color: #e6e6e6;
}

.dark .clear-rating-btn {
  background: #3d3d3d;
  border-color: #4a4a4a;
  color: #b3b3b3;
}

.dark .clear-rating-btn:hover {
  background: #4a4a4a;
  color: #e6e6e6;
}

/* 小红书iframe样式 */
.xhs-iframe {
  width: 100%;
  height: 400px;
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  background: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
}

.xhs-iframe:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  border-color: #42b883;
}

.dark .xhs-iframe:hover {
  border-color: #42b883;
  box-shadow: 0 4px 8px rgba(66, 184, 131, 0.2);
}

/* 深色模式下的空间选择器样式 */
.dark .space-option {
  color: #e6e6e6;
}

.dark .space-name {
  color: #e6e6e6;
}

.dark .space-desc {
  color: #b3b3b3;
}

.dark .space-color {
  border-color: rgba(255, 255, 255, 0.2);
}

.dark .space-count {
  color: #b3b3b3;
  background: #3d3d3d;
  border: 1px solid #4a4a4a;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .xhs-iframe {
    height: 300px;
  }

  .items-list.grid-layout {
    gap: 0.5rem;
  }

  .items-header {
    flex-direction: column;
    gap: 0.75rem;
    align-items: stretch;
    padding: 0;
  }

  .items-header h3 {
    text-align: center;
    font-size: 1.1rem;
  }

  .display-mode-toggle {
    justify-content: center;
    margin: 0 auto;
    width: fit-content;
  }

  .item-card {
    padding: 0.75rem;
    min-width: unset;
  }

  .item-header {
    flex-direction: column;
    gap: 0.5rem;
    align-items: flex-start;
  }

  .item-actions {
    opacity: 1;
  }

  .item-meta {
    flex-direction: column;
    gap: 0.5rem;
  }

  .dialog {
    width: 95%;
    margin: 1rem;
  }

  .dialog-header {
    padding: 1rem;
  }

  .dialog-form {
    padding: 1rem;
  }
}
</style>